// ===== 现代婚礼邀请函交互系统 =====

// 全局状态管理
const AppState = {
    currentSection: 'hero',
    currentGalleryCategory: 'all',
    currentImageIndex: 0,
    galleryImages: [],
    wishes: [],
    isLoading: true,
    isMobile: window.innerWidth <= 768
};

// 工具函数
const Utils = {
    // 防抖函数
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },

    // 节流函数
    throttle(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    },

    // 平滑滚动到指定元素
    scrollToElement(elementId, offset = 70) {
        const element = document.getElementById(elementId);
        if (element) {
            const elementPosition = element.getBoundingClientRect().top;
            const offsetPosition = elementPosition + window.pageYOffset - offset;
            
            window.scrollTo({
                top: offsetPosition,
                behavior: 'smooth'
            });
        }
    },

    // 检测元素是否在视口中
    isInViewport(element) {
        const rect = element.getBoundingClientRect();
        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
            rect.right <= (window.innerWidth || document.documentElement.clientWidth)
        );
    },

    // 格式化日期
    formatDate(date) {
        return new Intl.DateTimeFormat('zh-CN', {
            year: 'numeric',
            month: 'long',
            day: 'numeric',
            weekday: 'long'
        }).format(date);
    },

    // 生成唯一ID
    generateId() {
        return Date.now().toString(36) + Math.random().toString(36).substr(2);
    }
};

// 页面加载管理
const LoadingManager = {
    init() {
        this.showLoader();
        this.preloadImages();
        
        // 模拟加载时间，确保用户看到加载动画
        setTimeout(() => {
            this.hideLoader();
        }, 1500);
    },

    showLoader() {
        const loader = document.querySelector('.page-loader');
        if (loader) {
            loader.classList.remove('hidden');
        }
    },

    hideLoader() {
        const loader = document.querySelector('.page-loader');
        if (loader) {
            loader.classList.add('hidden');
            // 延迟移除元素，等待动画完成
            setTimeout(() => {
                loader.style.display = 'none';
            }, 500);
        }
    },

    // 预加载图片
    preloadImages() {
        const images = document.querySelectorAll('img[data-src]');
        const imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    img.src = img.dataset.src;
                    img.classList.add('loaded');
                    observer.unobserve(img);
                }
            });
        });

        images.forEach(img => imageObserver.observe(img));
    }
};

// 导航管理
const NavigationManager = {
    init() {
        // NavigationManager已移除navbar相关功能
    },

    bindEvents() {
        // 导航功能已移除
    },




};

// 故事时间线管理
const StoryTimelineManager = {
    currentChapter: 0,
    
    init() {
        this.bindEvents();
        this.loadStoryData();
    },
    
    bindEvents() {
        // 故事导航事件
        document.querySelectorAll('.story-nav-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const chapterIndex = parseInt(e.currentTarget.dataset.chapter);
                this.switchChapter(chapterIndex);
            });
        });
        
        // 图片点击事件
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('chapter-gallery-item-img')) {
                this.openModal(e.target.src, e.target.alt);
            }
        });
    },
    
    switchChapter(chapterIndex) {
        this.currentChapter = chapterIndex;
        
        // 更新导航按钮状态
        document.querySelectorAll('.story-nav-btn').forEach(btn => {
            btn.classList.toggle('active', parseInt(btn.dataset.chapter) === chapterIndex);
        });
        
        // 滚动到对应章节
        const targetChapter = document.querySelector(`[data-chapter="${chapterIndex}"]`);
        if (targetChapter) {
            targetChapter.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
    },
    
    loadStoryData() {
        // 检查是否有data.js中的数据
        if (typeof materialGroup !== 'undefined' && materialGroup.length > 0) {
            this.renderChaptersWithRealData();
        } else {
            console.warn('未找到data.js中的图片数据，使用默认数据');
            this.renderChaptersWithDefaultData();
        }
    },
    
    renderChaptersWithRealData() {
        window.materialGroup.forEach((group, index) => {
            // 更新章节标题和副标题
            this.updateChapterInfo(index, group);
            
            // 设置章节描述的滚动监听，而不是立即启动
            this.setupChapterDescriptionObserver(index, group.groupDesc);
            
            const chapterGallery = document.getElementById(`chapter-${index}-gallery`);
            if (!chapterGallery) return;
            
            const images = group.imageList || [];
            
            chapterGallery.innerHTML = images.map((img, imgIndex) => {
                // 计算图片的宽高比和合适的显示尺寸
                const aspectRatio = img.width / img.height;
                let displayWidth, displayHeight;
                
                // 根据宽高比设置合适的显示尺寸
                if (aspectRatio > 1.5) {
                    // 横图：宽度较大
                    displayWidth = '300px';
                    displayHeight = 'auto';
                } else if (aspectRatio < 0.7) {
                    // 竖图：高度较大
                    displayWidth = 'auto';
                    displayHeight = '400px';
                } else {
                    // 接近正方形
                    displayWidth = '250px';
                    displayHeight = '250px';
                }
                
                return `
                    <div class="chapter-gallery-item" data-aos="fade-up" data-aos-delay="${imgIndex * 100}" style="flex: 0 0 auto;">
                        <img src="${img.path}" 
                             alt="${group.groupName || '回忆'}${imgIndex + 1}" 
                             class="chapter-gallery-item-img"
                             style="width: ${displayWidth}; height: ${displayHeight}; object-fit: cover; border-radius: 8px;">
                    </div>
                `;
            }).join('');
            
            // 添加动画效果
            this.animateChapterGallery(chapterGallery);
        });
        
        // 创建底部滚动区域（如果不存在）
        this.createBottomLyricsArea();
    },
    
    // 更新章节信息（标题和副标题）
    updateChapterInfo(index, group) {
        const chapterElement = document.querySelector(`[data-chapter="${index}"]`);
        if (!chapterElement) return;
        
        const titleElement = chapterElement.querySelector('.chapter-title');
        const subtitleElement = chapterElement.querySelector('.chapter-subtitle');
        
        if (titleElement && group.groupName) {
            titleElement.textContent = group.groupName;
        }
        
        if (subtitleElement && group.groupSubName) {
            subtitleElement.textContent = group.groupSubName;
        }
    },
    
    // 设置章节描述的滚动监听
    setupChapterDescriptionObserver(index, description) {
        if (!description) return;
        
        const chapterElement = document.querySelector(`[data-chapter="${index}"]`);
        if (!chapterElement) return;
        
        // 只有第一个区域（index=0）才自动触发全屏播放
        if (index === 0) {
            // 创建Intersection Observer监听第一个章节进入视口
            const observer = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting && !entry.target.dataset.fullscreenTriggered) {
                        // 标记为已触发，防止重复触发
                        entry.target.dataset.fullscreenTriggered = 'true';
                        
                        // 获取章节数据
                        const chapterData = window.materialGroup?.[index];
                        if (chapterData) {
                            // 根据showType决定播放模式
                            const showType = chapterData.showType || 'image'; // 默认为图片模式
                            
                            if (showType === 'video' && chapterData.videoPath) {
                                // 启动全屏视频播放
                                FullscreenGalleryManager.startFullscreenVideoPlay(
                                    index,
                                    chapterData.videoPath,
                                    description
                                );
                            } else if (chapterData.imageList && chapterData.imageList.length > 0) {
                                // 启动全屏图片播放
                                FullscreenGalleryManager.startFullscreenPlay(
                                    index,
                                    chapterData.imageList,
                                    description
                                );
                            }
                        }
                        
                        // 停止观察该元素
                        observer.unobserve(entry.target);
                    }
                });
            }, {
                threshold: [0, 0.1, 0.2, 0.3, 0.5], // 多个阈值，确保能够触发
                rootMargin: '0px 0px 0px 0px' // 不设置边距，使用默认视口
            });
            
            // 开始观察第一个章节元素
            observer.observe(chapterElement);
        }
        // 其他章节不再自动触发全屏播放，移除滚动监听
    },
    
    // 按标点符号切分文字
    splitTextByPunctuation(text) {
        // 按句号、逗号、感叹号、问号等标点符号切分
        const segments = text.split(/([。，！？；：、])/)
            .filter(segment => segment.trim() !== '')
            .reduce((result, segment, index, array) => {
                // 将标点符号与前一个片段合并
                if (/[。，！？；：、]/.test(segment)) {
                    if (result.length > 0) {
                        result[result.length - 1] += segment;
                    }
                } else {
                    result.push(segment.trim());
                }
                return result;
            }, [])
            .filter(segment => segment.length > 0);
        
        return segments;
    },
    
    // 创建底部歌词滚动区域
    createBottomLyricsArea() {
        // 检查是否已存在
        if (document.getElementById('bottom-lyrics-area')) return;
        
        const lyricsArea = document.createElement('div');
        lyricsArea.id = 'bottom-lyrics-area';
        lyricsArea.className = 'bottom-lyrics-area';
        
        const lyricsContent = document.createElement('div');
        lyricsContent.className = 'bottom-lyrics-content';
        lyricsArea.appendChild(lyricsContent);
        
        document.body.appendChild(lyricsArea);
    },
    
    // 启动底部歌词滚动动画（只播放一次）
    startBottomLyricsAnimation(container, description, chapterIndex) {
        // 按标点符号切分描述文字
        const segments = this.splitTextByPunctuation(description);
        
        const bottomArea = document.getElementById('bottom-lyrics-area');
        const bottomContent = bottomArea.querySelector('.bottom-lyrics-content');
        let currentIndex = 0;
        
        // 清空之前的内容
        container.innerHTML = '';
        bottomContent.innerHTML = '';
        
        // 显示底部滚动区域
        bottomArea.style.display = 'flex';
        
        // 创建滚动动画函数
        const showNextSegment = () => {
            if (currentIndex < segments.length) {
                const segment = segments[currentIndex];
                
                // 在底部区域显示当前滚动的歌词
                bottomContent.innerHTML = `<div class="current-lyrics">${segment}</div>`;
                
                // 在lyrics-container中累积添加歌词
                const segmentElement = document.createElement('span');
                segmentElement.className = 'accumulated-lyrics';
                segmentElement.textContent = segment;
                
                // 添加到容器中
                if (container.children.length > 0) {
                    container.appendChild(document.createTextNode(' '));
                }
                container.appendChild(segmentElement);
                
                // 添加淡入动画
                segmentElement.style.opacity = '0';
                segmentElement.style.transform = 'translateY(10px)';
                
                setTimeout(() => {
                    segmentElement.style.opacity = '1';
                    segmentElement.style.transform = 'translateY(0)';
                    segmentElement.style.transition = 'all 0.6s ease-out';
                }, 100);
                
                currentIndex++;
                
                // 设置下一个片段的显示时间
                if (currentIndex < segments.length) {
                    setTimeout(showNextSegment, 2500); // 每2.5秒显示下一句
                } else {
                    // 所有片段显示完毕后，隐藏底部区域
                    setTimeout(() => {
                        bottomContent.innerHTML = '';
                        bottomArea.style.display = 'none';
                    }, 3000);
                }
            }
        };
        
        // 开始动画
        setTimeout(showNextSegment, 500); // 延迟0.5秒开始
    },
    
    renderChaptersWithDefaultData() {
        // 默认数据作为后备方案
        const defaultData = [
            {
                title: '相识',
                images: [
                    'https://picsum.photos/300/300?random=1',
                    'https://picsum.photos/300/300?random=2',
                    'https://picsum.photos/300/300?random=3',
                    'https://picsum.photos/300/300?random=4'
                ]
            },
            {
                title: '日常',
                images: [
                    'https://picsum.photos/300/300?random=5',
                    'https://picsum.photos/300/300?random=6',
                    'https://picsum.photos/300/300?random=7',
                    'https://picsum.photos/300/300?random=8',
                    'https://picsum.photos/300/300?random=9',
                    'https://picsum.photos/300/300?random=10'
                ]
            },
            {
                title: '婚纱照',
                images: [
                    'https://picsum.photos/300/300?random=11',
                    'https://picsum.photos/300/300?random=12',
                    'https://picsum.photos/300/300?random=13',
                    'https://picsum.photos/300/300?random=14',
                    'https://picsum.photos/300/300?random=15'
                ]
            }
        ];
        
        defaultData.forEach((chapter, index) => {
            const chapterGallery = document.getElementById(`chapter-${index}-gallery`);
            if (!chapterGallery) return;
            
            chapterGallery.innerHTML = chapter.images.map((imgSrc, imgIndex) => `
                <div class="chapter-gallery-item" data-aos="fade-up" data-aos-delay="${imgIndex * 100}">
                    <img src="${imgSrc}" alt="${chapter.title}${imgIndex + 1}" class="chapter-gallery-item-img">
                </div>
            `).join('');
            
            // 添加动画效果
            this.animateChapterGallery(chapterGallery);
        });
    },
    
    animateChapterGallery(galleryElement) {
        const items = galleryElement.querySelectorAll('.chapter-gallery-item');
        
        // 使用Intersection Observer来触发动画
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const item = entry.target;
                    const delay = parseInt(item.dataset.aosDelay) || 0;
                    
                    setTimeout(() => {
                        item.style.opacity = '1';
                        item.style.transform = 'translateY(0)';
                    }, delay);
                    
                    observer.unobserve(item);
                }
            });
        }, { threshold: 0.1 });
        
        items.forEach(item => {
            item.style.opacity = '0';
            item.style.transform = 'translateY(30px)';
            item.style.transition = 'all 0.6s ease';
            observer.observe(item);
        });
    },
    
    openModal(src, title) {
        ModalManager.open(src, title);
    }
};

// 模态框管理
const ModalManager = {
    init() {
        this.bindEvents();
    },

    bindEvents() {
        const modal = document.querySelector('.image-modal');
        const backdrop = document.querySelector('.modal-backdrop');
        const closeBtn = document.querySelector('.modal-close');
        const prevBtn = document.querySelector('.modal-prev');
        const nextBtn = document.querySelector('.modal-next');

        // 关闭模态框
        [backdrop, closeBtn].forEach(element => {
            if (element) {
                element.addEventListener('click', () => {
                    this.closeImageModal();
                });
            }
        });

        // 导航按钮
        if (prevBtn) {
            prevBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                this.previousImage();
            });
        }

        if (nextBtn) {
            nextBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                this.nextImage();
            });
        }

        // 键盘事件
        document.addEventListener('keydown', (e) => {
            if (modal && modal.classList.contains('show')) {
                switch(e.key) {
                    case 'Escape':
                        this.closeImageModal();
                        break;
                    case 'ArrowLeft':
                        this.previousImage();
                        break;
                    case 'ArrowRight':
                        this.nextImage();
                        break;
                }
            }
        });
    },

    openImageModal(index) {
        AppState.currentImageIndex = index;
        const modal = document.querySelector('.image-modal');
        const modalImage = document.querySelector('.modal-image');
        
        if (modal && modalImage) {
            const image = AppState.galleryImages[index];
            modalImage.src = image.src;
            modalImage.alt = image.alt;
            
            modal.classList.add('show');
            document.body.style.overflow = 'hidden';
            
            // 更新导航按钮状态
            this.updateModalNavigation();
        }
    },

    closeImageModal() {
        const modal = document.querySelector('.image-modal');
        if (modal) {
            modal.classList.remove('show');
            document.body.style.overflow = '';
        }
    },

    previousImage() {
        if (AppState.currentImageIndex > 0) {
            AppState.currentImageIndex--;
        } else {
            AppState.currentImageIndex = AppState.galleryImages.length - 1;
        }
        this.updateModalImage();
    },

    nextImage() {
        if (AppState.currentImageIndex < AppState.galleryImages.length - 1) {
            AppState.currentImageIndex++;
        } else {
            AppState.currentImageIndex = 0;
        }
        this.updateModalImage();
    },

    updateModalImage() {
        const modalImage = document.querySelector('.modal-image');
        if (modalImage) {
            const image = AppState.galleryImages[AppState.currentImageIndex];
            modalImage.src = image.src;
            modalImage.alt = image.alt;
            this.updateModalNavigation();
        }
    },

    updateModalNavigation() {
        const prevBtn = document.querySelector('.modal-prev');
        const nextBtn = document.querySelector('.modal-next');
        
        if (prevBtn) {
            prevBtn.style.opacity = AppState.galleryImages.length <= 1 ? '0.5' : '1';
        }
        if (nextBtn) {
            nextBtn.style.opacity = AppState.galleryImages.length <= 1 ? '0.5' : '1';
        }
    }
};



// 移动端优化
const MobileManager = {
    init() {
        this.detectMobile();
        this.bindTouchEvents();
        this.optimizeForMobile();
    },

    detectMobile() {
        AppState.isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || window.innerWidth <= 768;
        
        if (AppState.isMobile) {
            document.body.classList.add('mobile');
        }
    },

    bindTouchEvents() {
        if (!AppState.isMobile) return;

        let touchStartX = 0;
        let touchStartY = 0;
        
        // 图片模态框滑动切换
        const modal = document.querySelector('.image-modal');
        if (modal) {
            modal.addEventListener('touchstart', (e) => {
                touchStartX = e.touches[0].clientX;
                touchStartY = e.touches[0].clientY;
            }, { passive: true });
            
            modal.addEventListener('touchend', (e) => {
                const touchEndX = e.changedTouches[0].clientX;
                const touchEndY = e.changedTouches[0].clientY;
                
                const deltaX = touchEndX - touchStartX;
                const deltaY = touchEndY - touchStartY;
                
                // 水平滑动距离大于垂直滑动距离，且滑动距离足够
                if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > 50) {
                    if (deltaX > 0) {
                        ModalManager.previousImage();
                    } else {
                        ModalManager.nextImage();
                    }
                }
            }, { passive: true });
        }
    },

    optimizeForMobile() {
        if (!AppState.isMobile) return;

        // 防止双击缩放
        document.addEventListener('touchstart', function(event) {
            if (event.touches.length > 1) {
                event.preventDefault();
            }
        }, { passive: false });

        let lastTouchEnd = 0;
        document.addEventListener('touchend', function(event) {
            const now = (new Date()).getTime();
            if (now - lastTouchEnd <= 300) {
                event.preventDefault();
            }
            lastTouchEnd = now;
        }, { passive: false });

        // 优化滚动性能
        document.addEventListener('touchmove', function(event) {
            // 允许正常滚动
        }, { passive: true });
    }
};

// 动画管理
const AnimationManager = {
    init() {
        this.observeElements();
        this.addScrollAnimations();
    },

    observeElements() {
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.classList.add('animate-in');
                }
            });
        }, {
            threshold: 0.1,
            rootMargin: '0px 0px -50px 0px'
        });

        // 观察需要动画的元素
        document.querySelectorAll('.section-container, .detail-card, .gallery-item').forEach(el => {
            observer.observe(el);
        });
    },

    addScrollAnimations() {
        // 添加CSS动画类
        const style = document.createElement('style');
        style.textContent = `
            .animate-in {
                animation: slideInUp 0.6s ease-out;
            }
            
            @keyframes slideInUp {
                from {
                    opacity: 0;
                    transform: translateY(30px);
                }
                to {
                    opacity: 1;
                    transform: translateY(0);
                }
            }
            
            .success-message {
                animation: fadeInOut 3s ease-in-out;
            }
            
            @keyframes fadeInOut {
                0%, 100% { opacity: 0; }
                10%, 90% { opacity: 1; }
            }
        `;
        document.head.appendChild(style);
    }
};

// 倒计时管理
const CountdownManager = {
    init() {
        // 设置婚礼日期：2025年10月2日11:30
        this.weddingDate = new Date('2025-10-02T11:30:00');
        this.updateCountdown();
        
        // 每秒更新一次倒计时
        this.timer = setInterval(() => {
            this.updateCountdown();
        }, 1000);
    },
    
    updateCountdown() {
        const now = new Date().getTime();
        const distance = this.weddingDate.getTime() - now;
        
        // 如果婚礼已过，显示特殊信息
        if (distance < 0) {
            this.showWeddingPassed();
            return;
        }
        
        // 计算剩余时间
        const days = Math.floor(distance / (1000 * 60 * 60 * 24));
        const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((distance % (1000 * 60)) / 1000);
        
        // 更新显示
        this.updateDisplay(days, hours, minutes, seconds);
    },
    
    updateDisplay(days, hours, minutes, seconds) {
        const daysEl = document.getElementById('days');
        const hoursEl = document.getElementById('hours');
        const minutesEl = document.getElementById('minutes');
        const secondsEl = document.getElementById('seconds');
        
        if (daysEl) daysEl.textContent = days;
        if (hoursEl) hoursEl.textContent = hours;
        if (minutesEl) minutesEl.textContent = minutes;
        if (secondsEl) secondsEl.textContent = seconds;
    },
    
    showWeddingPassed() {
        const countdownContainer = document.querySelector('.countdown-container');
        if (countdownContainer) {
            countdownContainer.innerHTML = `
                <p class="countdown-title">我们已经结婚啦！</p>
                <div class="wedding-passed">
                    <span style="font-size: 2rem; color: var(--accent-color);">💕</span>
                </div>
            `;
        }
        
        // 清除定时器
        if (this.timer) {
            clearInterval(this.timer);
        }
    }
};

// 音乐管理器
const MusicManager = {
    init() {
        this.audio = document.getElementById('backgroundMusic');
        this.bindEvents();
        this.handleAutoplay();
    },

    bindEvents() {
        // 监听用户首次交互，尝试播放音乐
        const playOnInteraction = () => {
            this.playMusic();
            // 移除事件监听器，避免重复触发
            document.removeEventListener('click', playOnInteraction);
            document.removeEventListener('touchstart', playOnInteraction);
        };

        document.addEventListener('click', playOnInteraction);
        document.addEventListener('touchstart', playOnInteraction);
    },

    handleAutoplay() {
        // 尝试自动播放，如果失败则等待用户交互
        if (this.audio) {
            this.audio.play().catch(() => {
                console.log('自动播放被阻止，等待用户交互后播放音乐');
            });
        }
    },

    playMusic() {
        if (this.audio && this.audio.paused) {
            this.audio.play().catch(error => {
                console.log('音乐播放失败:', error);
            });
        }
    },

    pauseMusic() {
        if (this.audio && !this.audio.paused) {
            this.audio.pause();
        }
    },

    toggleMusic() {
        if (this.audio) {
            if (this.audio.paused) {
                this.playMusic();
            } else {
                this.pauseMusic();
            }
        }
    }
};

// 全屏图片播放器管理器
const FullscreenGalleryManager = {
    isPlaying: false,
    currentChapter: -1,
    currentImageIndex: 0,
    images: [],
    description: '',
    playInterval: null,
    descriptionContainer: null,
    // 视频播放相关属性
    isVideoMode: false,
    videoPath: '',
    videoElement: null,
    
    init() {
        this.createFullscreenContainer();
        this.bindEvents();
    },
    
    // 创建全屏容器
    createFullscreenContainer() {
        const container = document.createElement('div');
        container.id = 'fullscreen-gallery';
        container.className = 'fullscreen-gallery';
        container.innerHTML = `
            <div class="fullscreen-gallery-content">
                <!-- 顶部描述区域 -->
                <div class="fullscreen-description-top">
                    <div class="fullscreen-description-content"></div>
                </div>
                
                <!-- Slick轮播图容器 -->
                <div class="fullscreen-slider-container">
                    <div class="fullscreen-slider"></div>
                    
                    <!-- 图片计数器 -->
                    <div class="fullscreen-counter">1 / 1</div>
                </div>
                
                <!-- 关闭按钮 -->
                <button class="fullscreen-close" aria-label="关闭全屏">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                        <path d="M18 6L6 18M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                    </svg>
                </button>
                
                <!-- 下一章节按钮 -->
                <button class="fullscreen-next-chapter" aria-label="下一章节">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                        <path d="M9 18l6-6-6-6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                    <span>下一章节</span>
                </button>
            </div>
        `;
        document.body.appendChild(container);
        
        this.descriptionContainer = container.querySelector('.fullscreen-description-content');
        this.sliderContainer = container.querySelector('.fullscreen-slider');
    },
    
    // 绑定事件
    bindEvents() {
        const container = document.getElementById('fullscreen-gallery');
        const closeBtn = container.querySelector('.fullscreen-close');
        const nextChapterBtn = container.querySelector('.fullscreen-next-chapter');
        
        // 关闭按钮事件
        closeBtn.addEventListener('click', () => this.exitFullscreen());
        
        // 下一章节按钮事件
        nextChapterBtn.addEventListener('click', () => {
            this.switchToNextChapter();
        });
        
        // ESC键退出
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && this.isPlaying) {
                this.exitFullscreen();
            }
            // 左右箭头键切换图片（与slick轮播图配合）
            if (this.isPlaying) {
                if (e.key === 'ArrowLeft') {
                    this.previousImage();
                } else if (e.key === 'ArrowRight') {
                    this.nextImage();
                }
            }
        });
        
        // 点击背景退出
        container.addEventListener('click', (e) => {
            if (e.target === container) {
                this.exitFullscreen();
            }
        });
        
        // 添加触摸滑动事件监听
        this.bindSwipeEvents(container);
    },
    
    // 绑定滑动手势事件
    bindSwipeEvents(container) {
        let startY = 0;
        let startX = 0;
        let endY = 0;
        let endX = 0;
        let isSwipeDetected = false;
        
        // 触摸开始
        container.addEventListener('touchstart', (e) => {
            if (!this.isPlaying) return;
            
            const touch = e.touches[0];
            startY = touch.clientY;
            startX = touch.clientX;
            isSwipeDetected = false;
        }, { passive: true });
        
        // 触摸移动
        container.addEventListener('touchmove', (e) => {
            if (!this.isPlaying || isSwipeDetected) return;
            
            const touch = e.touches[0];
            endY = touch.clientY;
            endX = touch.clientX;
            
            const deltaY = startY - endY;
            const deltaX = Math.abs(startX - endX);
            
            // 检测向上滑动：垂直距离大于50px，水平距离小于垂直距离的一半（确保是垂直滑动）
            if (deltaY > 50 && deltaX < Math.abs(deltaY) / 2) {
                isSwipeDetected = true;
                this.switchToNextChapter();
            }
        }, { passive: true });
        
        // 触摸结束
        container.addEventListener('touchend', () => {
            startY = 0;
            startX = 0;
            endY = 0;
            endX = 0;
            isSwipeDetected = false;
        }, { passive: true });
    },
    
    // 切换到下一个章节的全屏播放
    switchToNextChapter() {
        const nextChapterIndex = this.currentChapter + 1;
        
        // 检查是否有下一个章节
        if (!window.materialGroup || nextChapterIndex >= window.materialGroup.length) {
            // 没有下一个章节，退出全屏
            this.exitFullscreen();
            return;
        }
        
        const nextChapterData = window.materialGroup[nextChapterIndex];
        if (!nextChapterData) {
            this.exitFullscreen();
            return;
        }
        
        // 停止当前播放但不退出全屏容器
        this.stopAutoPlay();
        if (this.videoElement) {
            this.videoElement.pause();
        }
        
        // 直接切换到下一个章节的内容
        const showType = nextChapterData.showType || 'image';
        const description = nextChapterData.groupDesc || '';
        
        if (showType === 'video' && nextChapterData.videoPath) {
            // 切换到全屏视频播放
            this.switchToVideoMode(nextChapterIndex, nextChapterData.videoPath, description);
        } else if (nextChapterData.imageList && nextChapterData.imageList.length > 0) {
            // 切换到全屏图片播放
            this.switchToImageMode(nextChapterIndex, nextChapterData.imageList, description);
        }
    },
    
    // 切换到视频模式（在全屏容器内）
    switchToVideoMode(chapterIndex, videoPath, description) {
        this.currentChapter = chapterIndex;
        this.isVideoMode = true;
        this.videoPath = videoPath;
        this.description = description;
        
        // 清空当前内容
        const container = document.getElementById('fullscreen-gallery');
        
        // 设置sliderContainer引用
        this.sliderContainer = container.querySelector('.fullscreen-slider');
        
        // 只清空slider内容，保留slider容器本身
        this.sliderContainer.innerHTML = '';
        
        // 创建视频播放器
        this.createVideoPlayer();
        
        // 重新开始描述动画
        this.startDescriptionAnimation();
        
        // 更新下一章节按钮状态
        this.updateNextChapterButton();
    },
    
    // 切换到图片模式（在全屏容器内）
    switchToImageMode(chapterIndex, images, description) {
        this.currentChapter = chapterIndex;
        this.isVideoMode = false;
        this.images = images;
        this.description = description;
        this.currentImageIndex = 0;
        
        // 清空当前内容
        const container = document.getElementById('fullscreen-gallery');
        
        // 设置sliderContainer引用
        this.sliderContainer = container.querySelector('.fullscreen-slider');
        
        // 只清空slider内容，保留slider容器本身
        this.sliderContainer.innerHTML = '';
        
        // 重新初始化轮播图
        this.initSlickSlider();
        
        // 开始自动播放
        this.startAutoPlay();
        
        // 重新开始描述动画
        this.startDescriptionAnimation();
        
        // 更新下一章节按钮状态
        this.updateNextChapterButton();
    },
    
    // 更新下一章节按钮状态
    updateNextChapterButton() {
        const container = document.getElementById('fullscreen-gallery');
        const nextChapterBtn = container.querySelector('.fullscreen-next-chapter');
        
        if (!nextChapterBtn) return;
        
        const nextChapterIndex = this.currentChapter + 1;
        const hasNextChapter = window.materialGroup && 
                              nextChapterIndex < window.materialGroup.length &&
                              window.materialGroup[nextChapterIndex];
        
        if (hasNextChapter) {
            nextChapterBtn.style.display = 'flex';
        } else {
            nextChapterBtn.style.display = 'none';
        }
    },
    
    // 开始全屏播放
    startFullscreenPlay(chapterIndex, images, description) {
        if (this.isPlaying) return;
        
        this.isPlaying = true;
        this.currentChapter = chapterIndex;
        this.currentImageIndex = 0;
        this.images = images;
        this.description = description;
        
        const container = document.getElementById('fullscreen-gallery');
        container.classList.add('active');
        
        // 禁用页面滚动
        document.body.style.overflow = 'hidden';
        
        // 初始化slick轮播图
        this.initSlickSlider();
        
        // 开始描述动画
        this.startDescriptionAnimation();
        
        // 更新下一章节按钮状态
        this.updateNextChapterButton();
    },
    
    // 开始全屏视频播放
    startFullscreenVideoPlay(chapterIndex, videoPath, description) {
        this.isVideoMode = true;
        this.videoPath = videoPath;
        this.currentChapter = chapterIndex;
        this.description = description;
        this.isPlaying = true;
        
        // 显示全屏容器
        this.fullscreenContainer.style.display = 'flex';
        document.body.style.overflow = 'hidden';
        
        // 创建视频播放器
        this.createVideoPlayer();
        
        // 开始描述动画
        this.startDescriptionAnimation();
        
        // 更新下一章节按钮状态
        this.updateNextChapterButton();
    },
    
    // 创建视频播放器
    createVideoPlayer() {
        // 检查容器是否存在
        if (!this.sliderContainer) {
            console.error('sliderContainer not found');
            return;
        }
        
        // 清空容器
        this.sliderContainer.innerHTML = '';
        
        // 创建视频元素
        this.videoElement = document.createElement('video');
        this.videoElement.src = this.videoPath;
        this.videoElement.controls = true;
        this.videoElement.autoplay = true;
        this.videoElement.muted = true; // 添加静音以支持自动播放
        this.videoElement.playsInline = true; // 移动端内联播放
        this.videoElement.style.cssText = `
            width: 100%;
            height: 100%;
            object-fit: contain;
            background: #000;
        `;
        
        // 尝试播放视频（处理自动播放限制）
        this.videoElement.addEventListener('loadeddata', () => {
            const playPromise = this.videoElement.play();
            if (playPromise !== undefined) {
                playPromise.catch(error => {
                    console.log('自动播放被阻止，需要用户交互:', error);
                    // 显示播放按钮提示用户点击
                    this.showPlayButton();
                });
            }
        });
        
        // 用户点击视频时取消静音
        this.videoElement.addEventListener('click', () => {
            if (this.videoElement.muted) {
                this.videoElement.muted = false;
            }
        });
        
        // 添加视频事件监听
        this.videoElement.addEventListener('ended', () => {
            // 视频播放结束后自动退出全屏
            setTimeout(() => {
                this.exitFullscreen();
            }, 2000);
        });
        
        // 将视频添加到容器
        this.sliderContainer.appendChild(this.videoElement);
    },
    
    // 显示播放按钮（当自动播放失败时）
    showPlayButton() {
        const playButton = document.createElement('div');
        playButton.className = 'video-play-button';
        playButton.innerHTML = `
            <div class="play-icon">▶</div>
            <div class="play-text">点击播放视频</div>
        `;
        playButton.style.cssText = `
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 20px;
            border-radius: 10px;
            cursor: pointer;
            text-align: center;
            z-index: 10;
            backdrop-filter: blur(10px);
        `;
        
        // 点击播放按钮时播放视频
        playButton.addEventListener('click', () => {
            this.videoElement.muted = false;
            this.videoElement.play();
            playButton.remove();
        });
        
        this.sliderContainer.appendChild(playButton);
    },
    
    // 初始化Slick轮播图
    initSlickSlider() {
        // 清空容器
        this.sliderContainer.innerHTML = '';
        
        // 添加图片到轮播图
        this.images.forEach((image, index) => {
            const slideDiv = document.createElement('div');
            slideDiv.innerHTML = `<img src="${image.path}" alt="第${index + 1}张图片" class="fullscreen-slide-image">`;
            this.sliderContainer.appendChild(slideDiv);
        });
        
        // 确保DOM更新后再初始化slick轮播图
        setTimeout(() => {
            // 销毁可能存在的slick实例
            if ($(this.sliderContainer).hasClass('slick-initialized')) {
                $(this.sliderContainer).slick('unslick');
            }
            
            // 初始化slick轮播图
            $(this.sliderContainer).slick({
                dots: false,
                infinite: true,
                speed: 1600, // 保持原有的1.6秒动画时长
                slidesToShow: 1,
                slidesToScroll: 1,
                autoplay: true,
                autoplaySpeed: 1500, // 保持原有的1.5秒自动播放间隔
                fade: false, // 使用滑动效果而不是淡入淡出
                cssEase: 'ease-out',
                arrows: false, // 禁用默认箭头，使用键盘和触摸控制
                swipe: true,
                touchMove: true,
                pauseOnHover: false,
                pauseOnFocus: false
            });
            
            // 绑定slick事件
             $(this.sliderContainer).on('afterChange', (event, slick, currentSlide) => {
                 this.currentImageIndex = currentSlide;
                 this.updateCounter();
             });
             
             
         }, 100);
        
        // 更新初始计数器
        this.updateCounter();
    },
    
    // 显示指定索引的图片（使用slick方法）
    showImage(index, direction = 'next') {
        if (!this.images || this.images.length === 0) return;
        
        // 确保索引在有效范围内，实现循环
        const newIndex = ((index % this.images.length) + this.images.length) % this.images.length;
        
        // 使用slick的goTo方法切换到指定图片
        $(this.sliderContainer).slick('slickGoTo', newIndex);
    },
    
    // 更新图片计数显示
    updateCounter() {
        const counterElement = document.querySelector('.fullscreen-counter');
        if (counterElement) {
            counterElement.textContent = `${this.currentImageIndex + 1} / ${this.images.length}`;
        }
    },
    
    // 切换到下一张图片
    nextImage() {
        $(this.sliderContainer).slick('slickNext');
    },
    
    // 切换到上一张图片
    previousImage() {
        $(this.sliderContainer).slick('slickPrev');
    },
    
    // 开始自动播放（slick已内置自动播放功能）
    startAutoPlay() {
        // slick轮播图已经在初始化时设置了autoplay，这里可以用来恢复自动播放
        $(this.sliderContainer).slick('slickPlay');
    },
    
    // 停止自动播放
    stopAutoPlay() {
        $(this.sliderContainer).slick('slickPause');
    },
    
    // 开始描述动画 - 固定显示所有歌词，逐行高亮
    startDescriptionAnimation() {
        if (!this.description) return;
        
        // 清空描述容器并设置歌词样式
        this.descriptionContainer.innerHTML = '';
        this.descriptionContainer.style.cssText = `
            position: relative;
            height: auto;
            max-height: 400px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            justify-content: flex-start;
            align-items: center;
            padding: 20px;
            background: linear-gradient(135deg, 
                rgba(0, 0, 0, 0.7) 0%, 
                rgba(0, 0, 0, 0.5) 50%, 
                rgba(0, 0, 0, 0.7) 100%);
            backdrop-filter: blur(10px);
            border-radius: 15px;
        `;
        
        // 按句子分割文字
        const sentences = this.splitTextByPunctuation(this.description);
        const lineDelay = 3000; // 每行间隔3000ms
        
        // 创建歌词容器
        const lyricsContainer = document.createElement('div');
        lyricsContainer.className = 'lyrics-static-container';
        lyricsContainer.style.cssText = `
            position: relative;
            width: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
        `;
        
        this.descriptionContainer.appendChild(lyricsContainer);
        
        // 预先创建所有歌词行并显示
        sentences.forEach((sentence, index) => {
            const lineElement = document.createElement('div');
            lineElement.className = 'lyrics-line';
            lineElement.textContent = sentence;
            lineElement.style.cssText = `
                opacity: 0.6;
                transform: scale(1);
                transition: all 0.8s cubic-bezier(0.25, 0.46, 0.45, 0.94);
                margin: 10px 0;
                line-height: 1.8;
                color: #f5f5f5;
                font-weight: 400;
                text-align: center;
                font-size: 0.8rem;
                text-shadow: 0 2px 12px rgba(0, 0, 0, 1), 0 0 8px rgba(255, 255, 255, 0.3);
                max-width: 90%;
                word-wrap: break-word;
                white-space: normal;
            `;
            
            lyricsContainer.appendChild(lineElement);
        });
        
        // 开始歌词高亮动画
        let currentIndex = 0;
        const animateLyrics = () => {
            if (!this.isPlaying || currentIndex >= sentences.length) return;
            
            const lines = lyricsContainer.querySelectorAll('.lyrics-line');
            
            // 重置所有行为默认样式
            lines.forEach((line, index) => {
                if (index < currentIndex) {
                    // 已播放的行 - 保持可见但不高亮
                    line.style.cssText = `
                        opacity: 0.7;
                        transform: scale(1);
                        transition: all 0.8s cubic-bezier(0.25, 0.46, 0.45, 0.94);
                        margin: 10px 0;
                        line-height: 1.8;
                        color: #d0d0d0;
                        font-weight: 400;
                        text-align: center;
                        font-size: 1.1rem;
                        text-shadow: 0 2px 8px rgba(0, 0, 0, 1);
                        max-width: 90%;
                        word-wrap: break-word;
                        white-space: normal;
                    `;
                } else if (index === currentIndex) {
                    // 当前行 - 高亮显示
                    line.style.cssText = `
                        opacity: 1;
                        transform: scale(1.05);
                        transition: all 0.8s cubic-bezier(0.25, 0.46, 0.45, 0.94);
                        margin: 10px 0;
                        line-height: 1.8;
                        color: #ffeb3b;
                        font-weight: 600;
                        text-align: center;
                        font-size: 1.0rem;
                        text-shadow: 0 0 25px rgba(255, 235, 59, 0.8), 0 0 40px rgba(255, 235, 59, 0.4), 0 2px 15px rgba(0, 0, 0, 1);
                        max-width: 90%;
                        word-wrap: break-word;
                        white-space: normal;
                    `;
                } else {
                    // 未播放的行 - 半透明
                    line.style.cssText = `
                        opacity: 0.5;
                        transform: scale(1);
                        transition: all 0.8s cubic-bezier(0.25, 0.46, 0.45, 0.94);
                        margin: 10px 0;
                        line-height: 1.8;
                        color: #a0a0a0;
                        font-weight: 300;
                        text-align: center;
                        font-size: 0.65rem;
                        text-shadow: 0 2px 6px rgba(0, 0, 0, 1);
                        max-width: 90%;
                        word-wrap: break-word;
                        white-space: normal;
                    `;
                }
            });
            
            currentIndex++;
            
            // 继续下一行
            setTimeout(animateLyrics, lineDelay);
        };
        
        // 延迟开始动画
        setTimeout(animateLyrics, 500);
    },
    
    // 分割文字（复用StoryTimelineManager的方法）
    splitTextByPunctuation(text) {
        return text.split(/([。！？；，、])/)
            .reduce((acc, part, index, array) => {
                if (index % 2 === 0) {
                    const nextPart = array[index + 1] || '';
                    const combined = (part + nextPart).trim();
                    if (combined) acc.push(combined);
                }
                return acc;
            }, [])
            .filter(sentence => sentence.length > 0);
    },
    
    // 退出全屏
    exitFullscreen() {
        if (!this.isPlaying) return;
        
        const currentChapterIndex = this.currentChapter;
        this.isPlaying = false;
        
        // 如果是视频模式，停止视频播放并清理
        if (this.isVideoMode && this.videoElement) {
            this.videoElement.pause();
            this.videoElement.src = '';
            this.videoElement.remove();
            this.videoElement = null;
        } else {
            // 停止自动播放（图片模式）
            this.stopAutoPlay();
            
            // 销毁slick轮播图
            if ($(this.sliderContainer).hasClass('slick-initialized')) {
                $(this.sliderContainer).slick('unslick');
            }
        }
        
        // 隐藏容器
        const container = document.getElementById('fullscreen-gallery');
        container.classList.remove('active');
        
        // 恢复页面滚动
        document.body.style.overflow = '';
        
        // 自动滚动到当前章节的顶部
        setTimeout(() => {
            const chapterElement = document.querySelector(`[data-chapter="${currentChapterIndex}"]`);
            if (chapterElement) {
                // 计算章节顶部位置
                const chapterRect = chapterElement.getBoundingClientRect();
                const chapterTop = chapterRect.top + window.pageYOffset;
                
                // 平滑滚动到章节顶部，留出一些缓冲空间
                window.scrollTo({
                    top: chapterTop - 100, // 留出100px的缓冲空间
                    behavior: 'smooth'
                });
            }
        }, 300); // 延迟300ms确保全屏动画完成
        
        // 重置状态
        this.currentChapter = -1;
        this.currentImageIndex = 0;
        this.images = [];
        this.description = '';
        this.isVideoMode = false;
        this.videoPath = '';
        
        // 清空描述容器
        if (this.descriptionContainer) {
            this.descriptionContainer.innerHTML = '';
        }
    }
};

// 主应用初始化
class WeddingApp {
    constructor() {
        this.init();
    }

    init() {
        // 等待DOM加载完成
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => {
                this.initializeApp();
            });
        } else {
            this.initializeApp();
        }
    }

    initializeApp() {
        console.log('🎉 婚礼邀请函应用初始化中...');
        
        try {
            // 为 story-chapter 元素添加初始加载类，确保动画只在页面初始加载时执行
            document.querySelectorAll('.story-chapter').forEach(chapter => {
                chapter.classList.add('initial-load');
            });
            
            // 初始化各个模块
            LoadingManager.init();
            NavigationManager.init();
            StoryTimelineManager.init();
            ModalManager.init();
            CountdownManager.init();
            MobileManager.init();
            AnimationManager.init();
            MusicManager.init();
            FullscreenGalleryManager.init();
            
            // 监听窗口大小变化
            window.addEventListener('resize', Utils.debounce(() => {
                AppState.isMobile = window.innerWidth <= 768;
                MobileManager.detectMobile();
            }, 250));
            
            console.log('✅ 婚礼邀请函应用初始化完成！');
            
        } catch (error) {
            console.error('❌ 应用初始化失败:', error);
        }
    }
}

// 启动应用
new WeddingApp();

// 导出到全局作用域（用于调试）
window.WeddingApp = {
    AppState,
    Utils,
    LoadingManager,
    NavigationManager,
    StoryTimelineManager,
    ModalManager,
    CountdownManager,
    MobileManager,
    AnimationManager,
    MusicManager,
    FullscreenGalleryManager
};